package com.example.artwindow.service.impl;

import ch.qos.logback.classic.spi.EventArgUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.artwindow.domain.dto.UserUpdateDTO;
import com.example.artwindow.domain.po.MyUserDetails;
import com.example.artwindow.domain.vo.CommentUserVO;
import com.example.artwindow.domain.vo.UserInfoVO;
import com.example.artwindow.domain.vo.UserLoginVO;
import com.example.artwindow.domain.dto.UserRegisterDTO;
import com.example.artwindow.constants.HttpCodeEnum;
import com.example.artwindow.exception.UnauthorizedException;
import com.example.artwindow.mapper.RolePermsMapper;
import com.example.artwindow.result.Result;
import com.example.artwindow.service.RolePermsService;
import com.example.artwindow.service.UserService;
import com.example.artwindow.domain.po.User;
import com.example.artwindow.mapper.UserMapper;
import com.example.artwindow.tool.CopyProperties;
import com.example.artwindow.tool.JwtTool;
import com.example.artwindow.tool.QiNiuOSTool;
import com.example.artwindow.tool.TheadLocalTool;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

/**
* @author EiEi
* @description 针对表【user_info(用户信息管理)】的数据库操作Service实现
* @createDate 2023-12-01 14:27:06
*/
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService , UserDetailsService {
	@Resource
	private RolePermsMapper rolePermsMapper;
	@Override
	public Result<?> userRegister(UserRegisterDTO userRegisterDTO) {
		//判断是否用户名重复
		QueryWrapper<User> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("username",userRegisterDTO.getUsername());
		if (userRegisterDTO.getUsername()==null){
			throw new UnauthorizedException(HttpCodeEnum.ERR_USERNAME_EXISTS);
		}
		if (count(queryWrapper)>0){
			throw new UnauthorizedException(HttpCodeEnum.ERR_USERNAME_EXISTS);
		}
		//封装数据
		User Ruser= new User();
		BeanUtil.copyProperties(userRegisterDTO,Ruser);
		Ruser.setUserType("1");
		Ruser.setCreateUser(1L);
		Ruser.setUpdateUser(1L);
		Ruser.setCreateTime(System.currentTimeMillis());
		Ruser.setUpdateTime( System.currentTimeMillis());
		Ruser.setMark(1);
		save(Ruser);
		return Result.success();
	}
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(User::getUsername,username);

		try {
			User one = getOne(lambdaQueryWrapper);
			return new MyUserDetails(one, rolePermsMapper.selectPermsByUserId(one.getId()));
		}catch (RuntimeException e){
			return null;
		}
	}
	@Override
	public Result<UserLoginVO> userLogin(User user) {
		String token = JwtTool.createToken(user.getId());
		UserLoginVO userLoginVO = BeanUtil.copyProperties(user, UserLoginVO.class);
		userLoginVO.setToken(token);
		return Result.success(userLoginVO);
	}

	@Override
	public Result<UserInfoVO> userSearch(Long id) {
		User byId = getById(id);
		UserInfoVO userInfoVo = new UserInfoVO();
		BeanUtils.copyProperties(byId, userInfoVo);
		return Result.success(userInfoVo);
	}

	@Override
	public Result<Null> userUpdate(UserUpdateDTO userUpdateDTO, MultipartFile profilePhoto) {
		Long id = TheadLocalTool.getCurrentId();
		//获取认证
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		//上传图片
		User user = BeanUtil.copyProperties(userUpdateDTO, User.class);
		String name = authentication.getName();
		if (!Objects.isNull(profilePhoto)){
			String movieCoverString = QiNiuOSTool.Os(name+System.currentTimeMillis(), profilePhoto);
			user.setProfilePhoto(movieCoverString);
		}
		user.setId(id);
		updateById(user);
		return Result.success();
	}

	@Override
	public Result<Null> userDelete() {
		removeById(TheadLocalTool.getCurrentId());
		return null;
	}



	public List<CommentUserVO> selectCommentUsers(List<Long> userIds){
		LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>();
		userLambdaQueryWrapper.in(User::getId,userIds);
		userLambdaQueryWrapper.select();
		List<User> userlist = list(userLambdaQueryWrapper);
		return CopyProperties.copyProperties(userlist, CommentUserVO.class);
	}

	//	@Override
//	public Result<UserLoginVO> userLogin(UserLoginDTO userLoginDTO) {
//		UserLoginVO userLoginVO = new UserLoginVO();
//		//查询用户信息
//		User loginUser = lambdaQuery().eq(User::getUsername, userLoginDTO.getUsername()).one();
//		//验证用户名
//		if (Objects.isNull(loginUser)){
//			return Result.error(HttpCodeEnum.ERR_USER_NOT_EXISTS.getMsg(), HttpCodeEnum.ERR_USER_NOT_EXISTS.getCode());
//		}
//
//		//验证密码
//		if (!Objects.equals(userLoginDTO.getPassword(), loginUser.getPassword())){
//			return Result.error(HttpCodeEnum.ERR_PASSWORD.getMsg(), HttpCodeEnum.ERR_PASSWORD.getCode());
//		}
//		//封装返回值
//		userLoginVO.setId(loginUser.getId());
//		userLoginVO.setName(loginUser.getName());
//		userLoginVO.setToken(JwtTool.createToken(loginUser.getId()));
//		return Result.success(userLoginVO);
//
//	}
}




